package com.newgoldcurrency.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.databinding.DialogBinding;
import com.newgoldcurrency.databinding.DialogDeleteAccountBinding;
import com.newgoldcurrency.databinding.DialogInputNameBinding;
import com.newgoldcurrency.databinding.DialogMineBinding;
import com.newgoldcurrency.databinding.DialogUpdateBinding;

import java.util.Formatter;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tools {
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        display.getMetrics(dm);
        return dm.widthPixels;
    }
    public static CharSequence checkTapHere(Context context,View.OnClickListener listener) {
        String content =context.getString(R.string.enter_middle_name_or_maiden_name);
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content);
        Matcher matcherRegistration = Pattern.compile("Tap here").matcher(spannableStringBuilder);
        while (matcherRegistration.find()) {
            spannableStringBuilder.setSpan(new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    listener.onClick(widget);
                }
                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(context.getResources().getColor(R.color.gold));
                    ds.setUnderlineText(true);
                }
            },matcherRegistration.start(), matcherRegistration.end(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        return spannableStringBuilder;
    }

    public static void dialog_delete_account(Activity activity,View.OnClickListener clickListener) {
        @NonNull DialogDeleteAccountBinding binding = DialogDeleteAccountBinding.inflate(activity.getLayoutInflater());
        AlertDialog dialog =new AlertDialog.Builder(activity).setView(binding.getRoot()).setCancelable(false).show();
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        p.width =(int) (screenWidthPixels(activity) * 0.8);
        dialog.getWindow().setAttributes(p);
        dialog.setCancelable(false);
        dialog.getWindow().setBackgroundDrawable(ResourcesCompat.getDrawable(activity.getResources(), R.drawable.transparent,null));
        binding.dialogDeleteAccountDelete.setOnClickListener(v -> {
            dialog.dismiss();
            clickListener.onClick(v);
        });
        binding.dialogDeleteAccountCancel.setOnClickListener(v -> dialog.dismiss());
    }
    public static CharSequence checkReadAutoLink(Context context) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(context.getString(R.string.check_text));
        Matcher matcherRegistration = Pattern.compile("《Use Agreement》").matcher(spannableStringBuilder);
        while (matcherRegistration.find()) {
            spannableStringBuilder.setSpan(new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    context.startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://goldrr.com/?useagreement/")));
                }
                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(context.getResources().getColor(R.color.glod));
                    ds.setUnderlineText(false);
                }
            },matcherRegistration.start(), matcherRegistration.end(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        Pattern patternPrivacy = Pattern.compile("《Privacy Policy》");
        Matcher matcherPrivacy = patternPrivacy.matcher(spannableStringBuilder);
        while (matcherPrivacy.find()) {
            spannableStringBuilder.setSpan(new  ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    context.startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://goldrr.com/?privacypolicy/")));
                }
                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(context.getResources().getColor(R.color.glod));
                    ds.setUnderlineText(false);
                }
            }, matcherPrivacy.start(), matcherPrivacy.end(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        return spannableStringBuilder;
    }
    public static void dialog_input_name(Activity activity,View.OnClickListener clickListener) {
        @NonNull DialogInputNameBinding binding = DialogInputNameBinding.inflate(activity.getLayoutInflater());
        AlertDialog dialog =new AlertDialog.Builder(activity).setView(binding.getRoot()).setCancelable(false).show();
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        p.width =(int) (screenWidthPixels(activity) * 0.6);
        dialog.getWindow().setAttributes(p);
        dialog.setCancelable(false);
        dialog.getWindow().setBackgroundDrawable(ResourcesCompat.getDrawable(activity.getResources(), R.drawable.transparent,null));
        binding.dialogInputSave.setOnClickListener(v -> {
            dialog.dismiss();
            clickListener.onClick(v);
        });
        binding.dialogInputClose.setOnClickListener(v -> dialog.dismiss());
    }
    public static boolean passwordNotFormat(String password){
       return !password.matches("^(?=.*\\d)(?=.*[a-zA-Z])[\\da-zA-Z!@#$%^&*()_+-=;:'|{},<.>/?`~]{6,20}+$");
    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    public static void update(Activity activity,String title,String content,boolean isForceUpdate,UpdateCallback updateCallback1,UpdateCallback updateCallback) {
        @NonNull DialogUpdateBinding binding = DialogUpdateBinding.inflate(activity.getLayoutInflater());
        binding.updateDialogTitle.setText(title);
        binding.updateDialogContent.setText(content);
        binding.updateDialogContent.setText(content);
        AlertDialog dialog=new AlertDialog.Builder(activity).setView(binding.getRoot()).show();
        if (isForceUpdate){
            dialog.setCancelable(false);
            binding.updateDialogRemaining.setVisibility(View.GONE);
        }else {
            binding.updateDialogRemaining.setVisibility(View.VISIBLE);
        }
        binding.updateDialogRemaining.setOnClickListener(view ->{
            dialog.dismiss();
            updateCallback1.update();
        });
        binding.updateDialogUpdate.setOnClickListener(view -> {
            if (!isForceUpdate)dialog.dismiss();
            updateCallback.update();
        });
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        p.width = ((int)(screenWidthPixels(activity) * 0.9));
        p.gravity = Gravity.BOTTOM;
        p.verticalMargin=0.04F;
        dialog.getWindow().setAttributes(p);
        dialog.getWindow().setBackgroundDrawable(ResourcesCompat.getDrawable(activity.getResources(), R.drawable.dialogbg, null));
    }
    public static boolean isWifiProxy(){
        String proxyAddress = System.getProperty("http.proxyHost");
        String portStr = System.getProperty("http.proxyPort");
        int proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
        return (!TextUtils.isEmpty(proxyAddress))&&(proxyPort!=-1);
    }
    public static boolean isReal() {
        String arch = System.getProperties().getProperty("os.arch").toUpperCase(Locale.ROOT);
        return !(TextUtils.equals(arch, "I686") || TextUtils.equals(arch, "I386") || TextUtils.equals(arch, "I486") || TextUtils.equals(arch, "I586"));
    }
    public static void toast(String string) {
        Toast.makeText(App.instance, string, Toast.LENGTH_LONG).show();
    }
    public static boolean isEmail(String email) {
        if (null == email || "".equals(email)) return false;
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        return p.matcher(email).matches();
    }
    public static boolean isCode(String ue){
        if (ue == null || ue.equals("")) return false;
        return Pattern.compile("^[A-Za-z0-9]{6,20}").matcher(ue).matches();
    }
    public static String stringForTime(int timeMs) {
        if (timeMs <= 0 || timeMs >= 24 * 60 * 60 * 1000) return "00:00";
        int totalSeconds = timeMs / 1000;
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;
        StringBuilder stringBuilder = new StringBuilder();
        Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
        if (hours > 0) return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        else return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
    public static void dialog_mine(Activity activity, String title, String content,String buttonText, boolean dismiss,View.OnClickListener clickListener) {
        @NonNull DialogMineBinding binding = DialogMineBinding.inflate(activity.getLayoutInflater());
        binding.dialogMineContent.setText(content);
        binding.dialogMineTitle.setText(title);
        binding.dialogMineConfirm.setText(buttonText);
        AlertDialog dialog =new AlertDialog.Builder(activity).setView(binding.getRoot()).setCancelable(false).show();
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        p.width =(int) (screenWidthPixels(activity) * 0.8);
        dialog.getWindow().setAttributes(p);
        dialog.setCancelable(false);
        dialog.getWindow().setBackgroundDrawable(ResourcesCompat.getDrawable(activity.getResources(), R.drawable.transparent,null));
        binding.dialogMineConfirm.setOnClickListener(v -> {
            if (dismiss) dialog.dismiss();
            clickListener.onClick(v);
        });
    }
    public static void log(String m){
        if (App.debug)Log.i("emmmmmmmmm", m);
    }
    public static void dialog(Activity activity, String title, String content,String confirmButtonText,String cancelButtonText,View.OnClickListener clickListener) {
        @NonNull DialogBinding binding = DialogBinding.inflate(activity.getLayoutInflater());
        binding.dialogContent.setText(content);
        binding.dialogTitle.setText(title);
        binding.dialogConfirm.setText(confirmButtonText);
        binding.dialogCancel.setText(cancelButtonText);
        AlertDialog dialog =new AlertDialog.Builder(activity).setView(binding.getRoot()).setCancelable(false).show();
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        p.width =(int) (screenWidthPixels(activity) * 0.8);
        dialog.getWindow().setAttributes(p);
        dialog.setCancelable(false);
        dialog.getWindow().setBackgroundDrawable(ResourcesCompat.getDrawable(activity.getResources(), R.drawable.transparent,null));
        binding.dialogConfirm.setOnClickListener(v -> {
            dialog.dismiss();
            clickListener.onClick(v);
        });
        binding.dialogCancel.setOnClickListener(v -> dialog.dismiss());
    }
    public static int screenWidthPixels(Context context){
        return context.getResources().getDisplayMetrics().widthPixels;
    }
    public static boolean isJson(String jsonStr) {
        JsonElement jsonElement;
        try {
            jsonElement = JsonParser.parseString(jsonStr);
        } catch (Exception e) {
            return false;
        }
        if (jsonElement == null) {
            return false;
        }
        return jsonElement.isJsonObject();
    }
}
